<?php
/**
 * Created by PhpStorm.
 * User: czh
 * Date: 2018/10/24
 * Time: 17:04
 */

//连接数据库
function connect_to_db()
{
    global $CONFIG;
    $conn = mysql_connect('sh-cdb-oqsr2dxe.sql.tencentcdb.com:62768', 'root', 'mojitoVlinked1024');
    mysql_select_db('share_battery', $conn);
    $query = "Set Names 'utf8mb4'";
    mysql_query($query, $conn);
    return $conn;
}

function json_encode_cn($struct)
{
    return preg_replace("/\\\\u([a-f0-9]{4})/e",
        "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($struct));
}

//IP地址归化
function ipFilter($key)
{
    $key = preg_replace("/[^0-9.]/", "", $key);
    return preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $key) ? $key :
        "0.0.0.0";
}

//获取客户端ip
function getClientIP()
{
    $ipstr = "";
    if (isset($_SERVER['HTTP_CLIENT_IP']) and !empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ipstr .= ipFilter($_SERVER['HTTP_CLIENT_IP']) . ",";
    }
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) and !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ipstr .= $_SERVER['HTTP_X_FORWARDED_FOR'] . ",";
    }
    if (isset($_SERVER['HTTP_PROXY_USER']) and !empty($_SERVER['HTTP_PROXY_USER'])) {
        $ipstr .= ipFilter($_SERVER['HTTP_PROXY_USER']) . ",";
    }
    if (isset($_SERVER['REMOTE_ADDR']) and !empty($_SERVER['REMOTE_ADDR'])) {
        $ipstr .= ipFilter($_SERVER['REMOTE_ADDR']) . ",";
    }

    $ip = strtok($ipstr, ",");
    do {
        $ip = trim($ip);
        if (empty($ip)) {
            continue;
        }

        $ip = ip2long($ip);

        //-------------------
        // skip private ip ranges
        //-------------------
        // 10.0.0.0 - 10.255.255.255
        // 172.16.0.0 - 172.31.255.255
        // 192.168.0.0 - 192.168.255.255
        // 127.0.0.1, 255.255.255.255, 0.0.0.0
        //-------------------
        if (!(($ip == 0) or ($ip == (int)0xFFFFFFFF) or ($ip == 0x7F000001) or (($ip >=
                    0x0A000000) and ($ip <= 0x0AFFFFFF)) or (($ip >= (int)0xC0A80000) and ($ip <= (int)
                    0xC0A8FFFF)) or (($ip >= (int)0xAC100000) and ($ip <= (int)0xAC1FFFFF)))
        ) {
            return long2ip($ip);
        }
    } while ($ip = strtok(','));

    //      return "0.0.0.0";
    return ipFilter($_SERVER['REMOTE_ADDR']);
}

//获取url内容
function fetchUrlContent($url, $timeout = 10)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_USERAGENT,
        'Mozilla/5.0 (Windows NT 6.1; rv:17.0) Gecko/20100101 Firefox/17.0');
    $rawResult = @curl_exec($ch);
    $curl_errno = curl_errno($ch);
    $curl_error = curl_error($ch);
    curl_close($ch);

    if ($curl_errno > 0) {
        return "Curl Error ($curl_errno): $curl_error\n";
    } else {
        return $rawResult;
    }
}



